package crmdna.mail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;

import com.microtripit.mandrillapp.lutung.MandrillApi;
import com.microtripit.mandrillapp.lutung.model.MandrillApiError;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage.Recipient;

public class Mandrill {
	
public static void sendMail(String emailAddress, String apiKey, String fromEmail, String fromName, String subject, String htmlContent) {
		
		MandrillMessage message = new MandrillMessage();
		message.setSubject(subject);
		message.setHtml(htmlContent);
		message.setAutoText(true);
		message.setTrackClicks(true);
		message.setTrackOpens(true);		
		message.setFromEmail(fromEmail);
		message.setFromName(fromName);
		
		ArrayList<Recipient> rcps = new ArrayList<Recipient>();
		Recipient rcp = new Recipient();
		rcp.setEmail(emailAddress);
		rcps.add(rcp);
		message.setTo(rcps);
		
		Logger logger = Logger.getLogger(Mandrill.class.getName());
		
		try {
			MandrillApi mandrillApi = new MandrillApi(apiKey);
			logger.info("about to send");
			mandrillApi.messages().send(message, false); 
			logger.info("Email \"" + subject + "\" to " + emailAddress);
		}
		catch (MandrillApiError ex) {
			logger.warning("MandrillApiError: \"" + subject + "\" to " + emailAddress + ": failed -> " +  ex.toString());
		}
		catch (IOException ex) {
			logger.warning("IOException: \"" + subject + "\" to " + emailAddress + ": failed -> " +  ex.toString());
		}
	}
}